const {
    override,
    fixBabelImports,
    addLessLoader,
    addWebpackModuleRule,
    addWebpackAlias,
    adjustStyleLoaders,
    useBabelRc,
} = require("customize-cra")
const CompressionWebpackPlugin = require("compression-webpack-plugin")
const path = require("path")

// 设置端口号：
process.env.PORT = 8000

const closedMap = () => (config) => {
    config.devtool =
        config.mode === "development" ? "cheap-module-source-map" : false
    return config
}

//配置开发模式和打包模式
const addCustomize = () => (config) => {
    if (process.env.NODE_ENV === "production") {
        // 关闭sourceMap
        config.devtool = false
        // 配置打包后的文件位置(默认为build, 修改为dist)
        const paths = require("react-scripts/config/paths")
        paths.appBuild = path.join(path.dirname(paths.appBuild), "dist")
        config.output.path = path.join(path.dirname(config.output.path), "dist")
        // 添加js打包gzip配置
        config.plugins.push(
            new CompressionWebpackPlugin({
                test: /.js$|.css$/,
                threshold: 1024,
            })
        )
    }
    if (config.resolve) {
        config.resolve.extensions.push(".jsx")
    }
    return config
}

module.exports = override(
    addCustomize(),
    // 针对antd实现按需打包: 根据import来打包(使用babel-plugin-import)
    fixBabelImports("import", {
        libraryName: "antd",
        libraryDirectory: "es",
        style: true, // 自动打包相关的样式
    }),

    // 使用less-loader对源码中的less的变量进行重新指定
    addLessLoader({
        javascriptEnabled: true,
        modifyVars: { "@primary-color": "#1DA57A" },
        lessOptions: {
            javascriptEnabled: true,
            localIdentName: "[local]--[hash:base64:5]",
        },
    }),
    adjustStyleLoaders(({ use: [, , postcss] }) => {
        const postcssOptions = postcss.options
        postcss.options = { postcssOptions }
    }),
    // 配置路径别名
    addWebpackAlias({
        "@": path.resolve(__dirname, "./src"),
    }),
    closedMap(),
    useBabelRc(),
    addWebpackModuleRule({
        test: /\.(png|jpg|gif|jpeg|svg)$/i,
        use: [
            {
                loader: "url-loader",
                options: {
                    limit: 20 * 1024,
                    esModule: false,
                    outputPath: `static/imgs/`,
                },
            },
        ],
    })
)
